#!/bin/bash

echo "🔄 开始重启体育场馆预约系统服务..."

# 1. 结束所有相关的Python进程
echo "📋 步骤1: 查找并结束相关进程..."

# 查找运行在8080端口的进程
PORT_PROCESS=$(netstat -tlnp 2>/dev/null | grep ":8080 " | awk '{print $7}' | cut -d'/' -f1)
if [ ! -z "$PORT_PROCESS" ]; then
    echo "找到占用8080端口的进程: $PORT_PROCESS"
    kill -9 $PORT_PROCESS
    echo "✅ 已结束8080端口进程"
else
    echo "ℹ️  8080端口未被占用"
fi

# 查找包含run.py的Python进程
echo "查找run.py相关进程..."
RUN_PROCESSES=$(ps aux | grep "[r]un.py" | awk '{print $2}')
if [ ! -z "$RUN_PROCESSES" ]; then
    echo "找到run.py进程: $RUN_PROCESSES"
    echo $RUN_PROCESSES | xargs kill -9
    echo "✅ 已结束run.py进程"
else
    echo "ℹ️  未找到run.py进程"
fi

# 等待进程完全结束
echo "⏳ 等待进程完全结束..."
sleep 3

# 2. 验证端口是否已释放
echo "📋 步骤2: 验证端口状态..."
PORT_CHECK=$(netstat -tlnp 2>/dev/null | grep ":8080 " | awk '{print $7}' | cut -d'/' -f1)
if [ ! -z "$PORT_CHECK" ]; then
    echo "❌ 8080端口仍被占用，强制结束..."
    kill -9 $PORT_CHECK
    sleep 2
else
    echo "✅ 8080端口已释放"
fi

# 3. 启动服务
echo "📋 步骤3: 启动服务..."

# 激活虚拟环境并设置环境变量
source venv/bin/activate

# 设置环境变量
export PORT=8080
export HOST=0.0.0.0
export FLASK_ENV=development

echo "环境变量设置完成"

# 创建日志目录
mkdir -p logs

echo "🚀 启动服务..."

# 启动服务
python run.py > logs/restart.log 2>&1 &
SERVICE_PID=$!

echo "服务进程ID: $SERVICE_PID"

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 10

# 4. 验证服务状态
echo "📋 步骤4: 验证服务状态..."

# 检查进程是否还在运行
if ps -p $SERVICE_PID > /dev/null 2>&1; then
    echo "✅ 服务进程正在运行 (PID: $SERVICE_PID)"
else
    echo "❌ 服务进程已退出，查看日志:"
    tail -20 logs/restart.log
    exit 1
fi

# 检查端口是否监听
PORT_LISTEN=$(netstat -tlnp 2>/dev/null | grep ":8080 ")
if [ ! -z "$PORT_LISTEN" ]; then
    echo "✅ 8080端口正在监听"
    echo "   $PORT_LISTEN"
else
    echo "❌ 8080端口未监听，查看日志:"
    tail -20 logs/restart.log
    exit 1
fi

# 5. 显示服务信息
echo "🎉 服务重启完成！"
echo ""
echo "📊 服务状态:"
echo "  进程ID: $SERVICE_PID"
echo "  监听地址: http://0.0.0.0:8080"
echo "  本地访问: http://localhost:8080"
echo "  日志文件: logs/restart.log"
echo ""
echo "✨ 重启脚本执行完成！"
